<?php


namespace app\api\controller\User;


use app\api\controller\AppController;
use app\api\model\Coupon\CouponModel;
use app\api\model\User\UserCouponModel;
use app\Request;
use app\Utils\Util;
use think\facade\Db;

class UserCoupon extends AppController
{
    /**
     * @api {get} /get_user_coupon_list 获取优惠券列表
     * @apiGroup 用户
     * @apiParam {string} token Token (查询用户所有优惠券，只传token 其他为0)
     * @apiParam {int} type 类型 1：课程 2：商品 （传类型必传商品或课程ID）
     * @apiParam {int} goods_id 课程或商品ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiSuccessExample {json} 部分数据
     * {
     *   "id":"用户优惠券ID",
     *   "uid":"用户ID",
     *   "coupon_id":"优惠券ID",
     *   "coupon_title":"优惠券标题",
     *   "coupon_data":"优惠券信息",
     *   "status":"状态  0：未使用 1：已使用 -1 已失效",
     *   "label":"类型 1：课程，2：商品",
     *   "attr":"属性 1：立减 2：满减券 3：立减折扣 4：满减折扣",
     *   "type":"1：全场 2：指定商品",
     *   "goods_ids":"商品或者课程IDs",
     *   "amount":"抵扣金额",
     *   "start_time":"开始时间",
     *   "end_time":"结束时间"
     * }
     * @apiVersion 1.0.0
     */
    public function getUserCouponList(Request $request)
    {
        $param = $request->param();
        $label = !empty($param['type']) ? $param['type'] : 0;
        $goods_id = !empty($param['goods_id']) ? $param['goods_id'] : 0;

        //获取相关课程优惠券
        $cou_where = [
            ['type','=',2],
            ['start_time','<',date("Y-m-d H:i:s",time())],
            ['end_time','>',date("Y-m-d H:i:s",time())]
        ];
        $cou_where_1 = [
            ['type','=',1],
            ['start_time','<',date("Y-m-d H:i:s",time())],
            ['end_time','>',date("Y-m-d H:i:s",time())]
        ];
        if(!empty($label)){
            array_push($cou_where,['label','=',$label]);
            array_push($cou_where_1,['label','=',$label]);
            array_push($cou_where, ['goods_ids','like','%'.$goods_id.','.'%']);
        }
        if(!empty($this->user)){
            array_push($cou_where,['uid','=',$this->user['id']]);
            array_push($cou_where_1,['uid','=',$this->user['id']]);
        }
        $coupon_list = UserCouponModel::getUserCouponWhereOrMore([$cou_where,$cou_where_1]);
        foreach ($coupon_list as &$item){
            $coupon_data = json_decode($item['coupon_data'],true);
            $item['coupon_title'] = $coupon_data['coupon_title'];
            $item['coupon_data'] = $coupon_data;
        }
        unset($item);
        $coupon_list = !empty($coupon_list) ? $coupon_list : [];
        return Util::returnJson(self::CODE_SUCCESS,$coupon_list);
    }

    /**
     * @api {post} /get_user_coupon 领取优惠券
     * @apiGroup 用户
     * @apiParam {string} token Token (查询用户所有优惠券，只传token 其他为0)
     * @apiParam {int} id 优惠券ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getUserCoupon(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if(empty($param['id'])){
            return Util::returnJson(self::CODE_ERROR,null,"参数错误！");
        }
        $coupon = CouponModel::getCouponWhere([['id','=',$param['id']]]);
        if(!empty($coupon)){
            if(!empty($coupon['is_level'])){
                if(empty($user['is_level_type'])){
                    if(empty($user['level_id']) || strtotime($user['end_time']) < time()){
                        return Util::returnJson(self::CODE_ERROR,null,"会员才能领取！");
                    }
                }
            }
            $user_coupon = UserCouponModel::getUserCouponWhere([['uid','=',$user['id']],['coupon_id','=',$coupon['id']]]);
            if(!empty($user_coupon)){
                return Util::returnJson(self::CODE_ERROR,null,"你已领取优惠券！");
            }
        }else{
            return Util::returnJson(self::CODE_ERROR,null,"优惠券错误");
        }
        $data = [
            'uid'          => $user['id'],
            'coupon_id'    => $coupon['id'],
            'coupon_data'  => json_encode($coupon),
            'status'       => 0,
            'up_time'      => date("Y-m-d H:i:s",time()),
            'add_time'     => date("Y-m-d H:i:s",time()),
            'label'        => $coupon['label'],
            'mer_id'       => $coupon['mer_id'],
            'attr'         => $coupon['attr'],
            'type'         => $coupon['type'],
            'goods_ids'    => $coupon['goods_ids'],
            'amount'       => $coupon['amount'],
            'total_amount' => $coupon['total_amount'],
            'start_time'   => $coupon['start_time'],
            'end_time'     => $coupon['end_time'],
        ];
        Db::startTrans();
        try {
            $id = UserCouponModel::addUserCoupon($data);
            if($id){
                $flag = CouponModel::couponReceiveIn($coupon['id'],1);
                if($flag){
                    Db::commit();
                    return Util::returnJson(self::CODE_SUCCESS,null,"领取成功！");
                }else{
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR,null,"领取失败3！");
                }
            }else{
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR,null,"领取失败2！");
            }
        }catch (\Exception $e){
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR,null,"领取失败1！");
        }
    }

}